/*
 * 
 * 
 * 
 */
package com.quhaodian.plug.data.plugs.diskfile;

import com.quhaodian.plug.api.StoragePlugin;
import com.quhaodian.plug.data.entity.PluginConfig;
import com.quhaodian.plug.data.vo.FileInfo;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Plugin - 本地文件存储
 */
@Component("diskFilePlugin")
public class DiskFilePlugin extends StoragePlugin {


    @Override
    public String getName() {
        return "磁盘存储";
    }

    @Override
    public String getVersion() {
        return "1.0";
    }

    @Override
    public String getAuthor() {
        return "ada.young";
    }

    @Override
    public String getSiteUrl() {
        return "";
    }

    @Override
    public String getInstallUrl() {
        return "admin/storage_plugin/diskfile/install.htm";
    }

    @Override
    public String getUninstallUrl() {
        return "admin/storage_plugin/diskfile/uninstall.htm";
    }

    @Override
    public String getSettingUrl() {
        return "admin/storage_plugin/diskfile/setting.htm";
    }

    @Override
    public void upload(String path, File file, String contentType) {
        PluginConfig pluginConfig = getPluginConfig();
        if (pluginConfig != null) {
            String disk = pluginConfig.getAttribute("disk");
            File destFile = new File(disk + path);
            try {
                FileUtils.moveFile(file, destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getUrl(String path) {
        PluginConfig pluginConfig = getPluginConfig();
        if (pluginConfig != null) {
            String url = pluginConfig.getAttribute("url");
            return url+path;
        }
        return path;
    }

    @Override
    public List<FileInfo> browser(String path) {
        List<FileInfo> fileInfos = new ArrayList<FileInfo>();
        PluginConfig pluginConfig = getPluginConfig();
        if (pluginConfig != null) {
            String disk = pluginConfig.getAttribute("disk");
            File directory = new File(disk + path);
            if (directory.exists() && directory.isDirectory()) {
                for (File file : directory.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(file.getName());
                    fileInfo.setUrl(path + file.getName());
                    fileInfo.setIsDirectory(file.isDirectory());
                    fileInfo.setSize(file.length());
                    fileInfo.setLastModified(new Date(file.lastModified()));
                    fileInfos.add(fileInfo);
                }
            }
        }

        return fileInfos;
    }

}